#import "MRCollectionView.h"

#pragma mark - 单元格
/*===================================================================
 说明:
	自定义布局单元格
 ==================================================================*/
@implementation MRCollectionViewCell

- (void)drawRect:(CGRect)rect
{
	if (_reflection)		//倒影处理
	{
		if (!_reflection.superview)
		{
			[self addSubview:_reflection];
			
			//渐变遮罩
			CAGradientLayer *gradient = [[CAGradientLayer alloc] init];
			
			gradient.colors = @[(id)rgba(0,0,0,.4).CGColor, (id)rgba(0,0,0,0).CGColor];
			gradient.startPoint = CGPointMake(.5, 0);
			gradient.endPoint = CGPointMake(.5, .6);
			
			//倒影为X轴镜像
			_reflection.layer.mask = gradient;
			//_reflection.layer.transform = CATransform3DMakeRotation(M_PI, 0, 1, 0);
		}
		
		CGRect frame = self.contentView.bounds;
		_reflection.frame = CGRectOffset(self.contentView.bounds, 0, CGRectGetMaxY(frame));
		_reflection.layer.mask.frame = _reflection.bounds;
		
		while (_reflection.subviews.count)
		{
			[_reflection.subviews.firstObject removeFromSuperview];
		}
		
		UIView *view = [self.contentView snapshotViewAfterScreenUpdates:YES];
		view.layer.transform = CATransform3DMakeRotation(M_PI, 1, 0, 0);
		
		[_reflection addSubview:view];
	}
}

@end

#pragma mark - 集合视图
/*===================================================================
 说明:
	集合视图
 ==================================================================*/
@implementation MRCollectionView
{
	UIPanGestureRecognizer		*_panGestureRecognizer;
	NSIndexPath					*_indexPath;
	__weak UICollectionViewCell	*_editingCell;
	__weak UIView				*_reflection;
	
	CGPoint		_centerCell, _centerReflection;
	
	MRCollectionViewCellEditingStyle	_editingStyle, _commitStyle;
}

- (void)awakeFromNib
{
	[super awakeFromNib];
	
	self.scrollsToTop = NO;
}

- (void)didMoveToSuperview
{
	[super didMoveToSuperview];
	
	_panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureRecognizer:)];
	_panGestureRecognizer.delegate = self;
	[self addGestureRecognizer:_panGestureRecognizer];
}

- (void)scrollToItemAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UICollectionViewScrollPosition)scrollPosition animated:(BOOL)animated
{
	CGPoint point = CGPointZero;
	MRCollectionViewLayout *layout = (MRCollectionViewLayout *)self.collectionViewLayout;
	
	if (layout.scrollDirection == UICollectionViewScrollDirectionVertical)
		point.y = indexPath.row * layout.itemSize.height;
	else
		point.x = indexPath.row * layout.itemSize.width;
	
	[self setContentOffset:point animated:animated];
}

- (NSIndexPath *)indexPathForItemAtPoint:(CGPoint)point
{
	MRCollectionViewLayout *layout = (MRCollectionViewLayout *)self.collectionViewLayout;
	CGSize size = layout.itemSize;
	NSUInteger count = [self numberOfItemsInSection:0];
	
	if (count == 0)
		return nil;
	else if (layout.scrollDirection == UICollectionViewScrollDirectionVertical)
		return [NSIndexPath indexPathForItem:MIN(count-1, (self.contentOffset.y + size.height / 2) / size.height) inSection:0];
	else
		return [NSIndexPath indexPathForItem:MIN(count-1, (self.contentOffset.x + size.width / 2) / size.width) inSection:0];
}

#pragma mark - 编辑手势
/*===================================================================
 说明:
	编辑手势处理
 ==================================================================*/
- (BOOL)gestureRecognizerShouldBegin:(UIPanGestureRecognizer *)gestureRecognizer
{
	MRCollectionViewLayout *layout = (MRCollectionViewLayout *)self.collectionViewLayout;
	
	if (gestureRecognizer == _panGestureRecognizer)
	{
		//当前编辑的单元格
		_indexPath = [super indexPathForItemAtPoint:[gestureRecognizer locationInView:self]];
		if (!_indexPath) return NO;
		
		_reflection = nil;
		_editingCell = [self cellForItemAtIndexPath:_indexPath];
		if ([_editingCell isKindOfClass:[MRCollectionViewCell class]]) _reflection = ((MRCollectionViewCell *)_editingCell).reflection;
		
		//当前布局滚动方向
		BOOL vertical = (layout.scrollDirection == UICollectionViewScrollDirectionVertical);
		
		//如果不编辑可用拖动方向则返回NO,让上层继续使用手势
		CGPoint translation = [gestureRecognizer translationInView:gestureRecognizer.view.superview];
		if (vertical && (ABS(translation.y) > ABS(translation.x)))
			return NO;
		else if (!vertical && (ABS(translation.x) > ABS(translation.y)))
			return NO;
		
		//如果单元格不是当前的也不能编辑
		if (vertical && _indexPath.row != round(self.contentOffset.y / layout.itemSize.height))
			return NO;
		else if (!vertical && _indexPath.row != round(self.contentOffset.x / layout.itemSize.width))
			return NO;
		
		//获取单元格可编辑类型
		if ([self.delegate respondsToSelector:@selector(collectionView:editingStyleAtIndexPath:)])
			_editingStyle = [(id)self.delegate collectionView:self editingStyleAtIndexPath:_indexPath];
		else
			return NO;
	}
	
	return YES;
}

- (void)panGestureRecognizer:(UIPanGestureRecognizer *)gestureRecognizer
{
	MRCollectionViewLayout *layout = (MRCollectionViewLayout *)self.collectionViewLayout;
	
	if (gestureRecognizer.state == UIGestureRecognizerStateBegan)
	{
		_centerCell = _editingCell.center;
		_centerReflection = _reflection.center;
	}
	else if (gestureRecognizer.state == UIGestureRecognizerStateChanged)
	{
		BOOL vertical = (layout.scrollDirection == UICollectionViewScrollDirectionVertical);
		CGPoint translation = [gestureRecognizer translationInView:gestureRecognizer.view.superview];
		
		if (vertical) {translation.y = 0; if (!_editingStyle) translation.x /= 3;}
		if (!vertical) {translation.x = 0; if (!_editingStyle) translation.y /= 3;}
		
		//单元格位置
		_editingCell.center = CGPointMake(_centerCell.x + translation.x, _centerCell.y + translation.y);
		
		//倒影位置(仅垂直编辑时有效)
		if (translation.y < 0)
		{
			_reflection.center = CGPointMake(_centerReflection.x, _centerReflection.y + translation.y * -2);
			_reflection.alpha  = 1.f + translation.y / _reflection.bounds.size.height;
		}
		else if (vertical)
		{
			_reflection.alpha = 1;
			_reflection.center = _centerReflection;
		}
		
		//编辑类型
	}
	else if (gestureRecognizer.state == UIGestureRecognizerStateEnded)
	{
		//CGPoint translation = [gestureRecognizer translationInView:gestureRecognizer.view.superview];
		//if (translation.)
		[self setEditing:NO animated:YES];
	}
	else
	{
		[self setEditing:NO animated:YES];
	}
}

/*===================================================================
 说明:
	编辑完成动画
 ==================================================================*/
- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
	if (!editing || (_commitStyle != MRCollectionViewCellEditingStyleDelete))
	{
		if (_editingCell.center.y < _centerCell.y)	//分离时使用跌落特效动画(意味着只在垂直编辑时有效)
		{
			CGFloat drop = .15;		//跌落系数
			
			//
			CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
			animation.duration = .3;
			//animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
			animation.values = @[[NSValue valueWithCGPoint:_editingCell.center],
								 [NSValue valueWithCGPoint:_centerCell],
								 [NSValue valueWithCGPoint:CGPointMake(_centerCell.x, (_editingCell.center.y - _centerCell.y) * drop + _centerCell.y)],
								 [NSValue valueWithCGPoint:_centerCell]];
			
			[_editingCell.layer addAnimation:animation forKey:@"position"];
			
			//
			animation.values = @[[NSValue valueWithCGPoint:_reflection.center],
								 [NSValue valueWithCGPoint:_centerReflection],
								 [NSValue valueWithCGPoint:CGPointMake(_centerReflection.x, (_reflection.center.y - _centerReflection.y) * drop + _centerReflection.y)],
								 [NSValue valueWithCGPoint:_centerReflection]];
			
			[_reflection.layer addAnimation:animation forKey:@"position"];
			
			//
			CAKeyframeAnimation *animation1 = [CAKeyframeAnimation animationWithKeyPath:@"opacity"];
			animation1.duration = animation.duration;
			//animation1.timingFunction = animation.timingFunction;
			animation1.values = @[[NSNumber numberWithFloat:_reflection.alpha],
								  [NSNumber numberWithFloat:1],
								  [NSNumber numberWithFloat:1.f - (1.f - _reflection.alpha) * drop],
								  [NSNumber numberWithFloat:1]];
			
			[_reflection.layer addAnimation:animation1 forKey:@"opacity"];
			
			_editingCell.layer.position = _centerCell;
			_reflection.layer.opacity   = 1;
			_reflection.layer.position  = _centerReflection;
		}
		else	//常规动画
		{
			[UIView animateWithDuration:(animated ? .25 : 0) animations:^{
				_editingCell.center = _centerCell;
				_reflection.alpha   = 1;
				_reflection.center  = _centerReflection;
			}];
		}
	} else if (_commitStyle == MRCollectionViewCellEditingStyleDelete)	//删除时动画
	{
		[UIView animateWithDuration:(animated ? .25 : 0) animations:^{
			
			_reflection.alpha   = 0;
			
		} completion:^(BOOL finished) {
			//动画完成时从集合中删除
		}];
	}
}

@end
